#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
资料审核

"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
from datetime import datetime

from django.shortcuts import render, reverse, redirect

from django.contrib.auth import get_user
from django.contrib.auth.decorators import login_required, permission_required

from django.http import HttpResponse, HttpResponseRedirect

from smAdmin.models import SmerpErpinfo, SmerpAccount, SmerpBrand, SmerpProduct, SmerpMaterial, CHECK_STATUS_CHOICES

from smAdmin.jqgrid import JqGrid

import logging

# Get an instance of a logger
logger = logging.getLogger('smAdmin')


# -------------企业列表------------------
class SmerpErpinfoGrid(JqGrid):
	model = SmerpErpinfo  # could also be a queryset
	fields = ['id',
			  'full_name',
			  'check_status',
			  'smerpaccount__email',
			  # 'organization_code',
			  # 'registration_no',
			  # 'representative',
			  # 'scope_normal',
			  # 'scope_special',
			  # 'staff_num',
			  # 'licence_img',
			  # 'manager',
			  # 'manager_phone',
			  # 'manager_id_card_no',
			  # 'manager_id_card_img',
			  # 'create_time',
			  "submit_check_time",
			  'myac'
			  ]  # optional

	url = '/smAdmin/check/erpinfo_list'
	editurl = '/smAdmin/check/erpinfo_edit'
	caption = u'待审核企业列表'  # optional

	# 设置
	extra_config = {
		"sortname": "submit_check_time",  # 按时间提交审核的时间排序
	}
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'create_time': {
			"label": u"创建时间",
			"sorttype": 'date',
			"sortorder": 'asc',  # desc

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'width': 100
		},
		'smerpaccount__email': {
			"label": u"账号",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},

		'full_name': {
			"label": u"企业全称",

			"sortable": False,
			"sorttype": 'string',

			"editable": True,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'width': 100
		},
		'check_status': {
			"label": u"审核状态",
			"sorttype": 'integer',

			"editable": True,
			"edittype": 'select',
			"editoptions": {"value": "0:未提交;1:待审核;2:通过;3:驳回"},

			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "0:未提交;1:待审核;2:通过;3:驳回"},
			"sortable": False,
			'width': 100
		},

		'submit_check_time': {
			"label": u"提交审核时间",
			"sorttype": 'date',
			"sortorder": 'asc',  # desc

			"hidden": False,
			"sortable": False,
			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 100,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": False, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.check.erpinfo', ])
def erpinfo(request):
	"""
	企业信息
	:param request:
	:return:
	"""
	grid = SmerpErpinfoGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/check/erpinfo.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.erpinfo.list', ])
def erpinfo_list(request):
	"""
	待审核企业信息列表
	:param request:
	:return:
	"""
	# print request.GET.get('filters', '')

	filters = request.GET.get('filters')
	if filters:
		filters = json.loads(filters)
	else:
		filters = {"groupOp": "AND", "rules": []}
	# 添加只能够搜索待审核的企业
	rules = filters.get("rules")
	rules.append({"field": "check_status", "op": "cn", "data": "1"})
	request.GET._mutable = True
	request.GET.update({"filters": json.dumps(filters)})
	request.GET._mutable = False

	# print request.GET.get('filters', '')

	grid = SmerpErpinfoGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['check.erpinfo.add', 'check.erpinfo.edit', 'check.erpinfo.del'])
def erpinfo_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpErpinfoGrid()
	user = get_user(request)
	if oper == 'edit':
		if not user.has_perm('check.erpinfo.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('check.erpinfo.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('check.erpinfo.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.erpinfo.detail', ])
def erpinfo_detail(request):
	"""
	企业详情
	:param request:
	:return:
	"""
	id = request.GET.get('id')

	smerperpinfo = SmerpErpinfo.objects.get(id=id)
	smerpaccount = smerperpinfo.smerpaccount

	# 企业信息
	erp_info = []
	for field in smerperpinfo._meta.fields:
		field_name = field.name

		field_value = getattr(smerperpinfo, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("id", "smerpaccount", "passwd"):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		erp_info.append({"name": field_name, "label": label, "value": field_value})

	# 企业账号信息
	account = []
	for field in smerpaccount._meta.fields:
		field_name = field.name
		label = field.verbose_name
		field_value = getattr(smerpaccount, field.name)
		if field_value is None:
			field_value = ""

		# 标签
		label = field.verbose_name
		if field.choices:
			print field.choices
			for item in field.choices:
				print item
				if field_value == item[0]:
					field_value = item[1]
					break

		account.append({"name": field_name, "label": label, "value": field_value})

	context = {
		"erp_info": erp_info,
		"account": account,
	}
	return render(request, "smAdmin/check/erpinfo_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.erpinfo.check', ])
def erpinfo_submit_check_result(request):
	"""
	提交企业信息的审核结果
	:param request:
	:return:
	"""
	id = request.POST.get('id')  # 企业信息Id
	is_pass = request.POST.get('is_pass')  # 是否通过
	check_mark = request.POST.get('check_mark')  # 审核备注

	if not check_mark or len(check_mark) < 2:
		res = {"c": -1, "m": u"审核备注信息过短"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	if not id:
		res = {"c": -1, "m": u"参数错误，企业信息不存在"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	try:
		smerperpinfo = SmerpErpinfo.objects.get(id=id)
		if not smerperpinfo:
			res = {"c": -1, "m": u"参数错误，企业信息不存在"}
			return HttpResponse(json.dumps(res), content_type="application/json")

		if is_pass == "1":
			smerperpinfo.check_status = 2  # 审核通过
		else:
			smerperpinfo.check_status = 3  # 驳回
		smerperpinfo.check_mark = check_mark
		smerperpinfo.check_time = datetime.now()
		smerperpinfo.save()

		res = {"c": 0, "m": u"审核结果已经保存"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	except:
		logger.exception("")

	res = {"c": -99, "m": u"系统异常"}
	return HttpResponse(json.dumps(res), content_type="application/json")


# -------------品牌列表------------------
class SmerpBrandGrid(JqGrid):
	model = SmerpBrand  # could also be a queryset
	fields = ['id',
			  'name_zh',
			  'check_status',
			  'smerpaccount__smerperpinfo__full_name',
			  'name_en',
			  'logo',
			  'submit_check_time',
			  'myac'
			  ]  # optional
	url = '/smAdmin/check/brand_list'
	editurl = '/smAdmin/check/brand_edit'
	caption = u'待审核品牌列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'create_time': {
			"label": u"创建时间",

			'editable': False,
			"edittype": 'text',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			"hidden": True,
			'width': 100
		},
		'smerpaccount__smerperpinfo__full_name': {
			"label": u"所属企业",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			"editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},
		'name_zh': {
			"label": u"品牌名称",
			"sortable": False,

			"editable": True,
			"edittype": 'text',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'width': 100
		},
		'name_en': {
			"label": u"英文名称",
			"sortable": False,
			"sorttype": 'string',

			"editable": True,
			"edittype": 'text',

			"search": False,
			"stype": "text",

			"hidden": True,
			'width': 100
		},
		'check_status': {
			"label": u"审核状态",

			"sortable": False,
			"sorttype": 'integer',

			"editable": True,
			"edittype": 'select',
			"editoptions": {"value": "0:未提交;1:待审核;2:通过;3:驳回"},

			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "0:未提交;1:待审核;2:通过;3:驳回"},

			'width': 100
		},
		'logo': {
			"label": u"商标Logo",
			"sortable": False,

			"search": False,

			"hidden": True,
			'width': 100
		},
		'submit_check_time': {
			"label": u"提交审核时间",
			"sorttype": 'date',
			"sortorder": 'asc',  # desc

			"hidden": False,
			"sortable": False,
			'width': 100
		},
		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.check.brand', ])
def brand(request):
	"""
	品牌信息
	:param request:
	:return:
	"""
	grid = SmerpBrandGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/check/brand.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.brand.list', ])
def brand_list(request):
	filters = request.GET.get('filters')
	if filters:
		filters = json.loads(filters)
	else:
		filters = {"groupOp": "AND", "rules": []}
	# 添加只能够搜索待审核的企业
	rules = filters.get("rules")
	rules.append({"field": "check_status", "op": "cn", "data": "1"})
	request.GET._mutable = True
	request.GET.update({"filters": json.dumps(filters)})
	request.GET._mutable = False

	grid = SmerpBrandGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['check.brand.add', 'check.brand.edit', 'check.brand.del'])
def brand_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpBrandGrid()
	user = get_user(request)
	if oper == 'edit':
		if not user.has_perm('check.brand.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('check.brand.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('check.brand.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.brand.detail', ])
def brand_detail(request):
	id = request.GET.get('id')

	smerpbrand = SmerpBrand.objects.get(id=id)

	# 品牌信息
	brand_info = []
	for field in smerpbrand._meta.fields:
		field_name = field.name

		field_value = getattr(smerpbrand, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("smerpaccount",):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		brand_info.append({"name": field_name, "label": label, "value": field_value})

	brand_licenses = []
	for item in smerpbrand.smerpbrandlicenses.all():
		brand_licenses.append([item.name, item.img])

	products = []
	for item in smerpbrand.smerpproducts.all():
		check_status_str = ""
		for c in CHECK_STATUS_CHOICES:
			if item.check_status == c[0]:
				check_status_str = c[1]
				break

		products.append([item.name, check_status_str, item.create_time])

	context = {
		"brand_info": brand_info,
		"brand_licenses": brand_licenses,
		"products": products,
	}
	return render(request, "smAdmin/check/brand_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.brand.check', ])
def brand_submit_check_result(request):
	"""
	提交品牌信息的审核结果
	:param request:
	:return:
	"""
	id = request.POST.get('id')  # 品牌信息Id
	is_pass = request.POST.get('is_pass')  # 是否通过
	check_mark = request.POST.get('check_mark')  # 审核备注

	if not check_mark or len(check_mark) < 2:
		res = {"c": -1, "m": u"审核备注信息过短"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	if not id:
		res = {"c": -1, "m": u"参数错误，品牌信息不存在"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	try:
		smerpbrand = SmerpBrand.objects.get(id=id)
		if not smerpbrand:
			res = {"c": -1, "m": u"参数错误，品牌信息不存在"}
			return HttpResponse(json.dumps(res), content_type="application/json")

		if is_pass == "1":
			smerpbrand.check_status = 2  # 审核通过
		else:
			smerpbrand.check_status = 3  # 驳回

		smerpbrand.check_mark = check_mark
		smerpbrand.check_time = datetime.now()
		smerpbrand.save()

		res = {"c": 0, "m": u"审核结果已经保存"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	except:
		logger.exception("")

	res = {"c": -99, "m": u"系统异常"}
	return HttpResponse(json.dumps(res), content_type="application/json")


# -------------产品列表------------------
class SmerpProductGrid(JqGrid):
	model = SmerpProduct  # could also be a queryset
	fields = ['id',
			  'name',
			  'check_status',
			  'smerpbrand__name_zh',
			  'smerpaccount__smerperpinfo__full_name',
			  'create_time',
			  'submit_check_time',
			  'myac'
			  ]  # optional
	url = '/smAdmin/check/product_list'
	editurl = '/smAdmin/check/product_edit'
	caption = u'待审核产品列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'name': {
			"label": u"产品名称",
			"sortable": False,
			'width': 100
		},
		'smerpbrand__name_zh': {
			"label": u"所属品牌",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},
		'smerpaccount__smerperpinfo__full_name': {
			"label": u"所属企业",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			"editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},

		'check_status': {
			"label": u"审核状态",
			"sortable": False,
			'width': 100
		},

		'submit_check_time': {
			"label": u"提交审核时间",
			"sorttype": 'date',
			"sortorder": 'asc',  # desc

			"hidden": False,
			"sortable": False,
			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.check.product', ])
def product(request):
	"""
	产品信息
	:param request:
	:return:
	"""
	grid = SmerpProductGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/check/product.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.product.list', ])
def product_list(request):
	filters = request.GET.get('filters')
	if filters:
		filters = json.loads(filters)
	else:
		filters = {"groupOp": "AND", "rules": []}
	# 添加只能够搜索待审核的企业
	rules = filters.get("rules")
	rules.append({"field": "check_status", "op": "cn", "data": "1"})
	request.GET._mutable = True
	request.GET.update({"filters": json.dumps(filters)})
	request.GET._mutable = False

	grid = SmerpProductGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['check.product.add', 'check.product.edit', 'check.product.del'])
def product_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpProductGrid()
	user = get_user(request)
	if oper == 'edit':
		if not user.has_perm('check.product.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('check.product.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('check.product.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.product.detail', ])
def product_detail(request):
	id = request.GET.get('id')

	smerpprduct = SmerpProduct.objects.get(id=id)

	# 产品信息
	product_info = []
	for field in smerpprduct._meta.fields:
		field_name = field.name

		field_value = getattr(smerpprduct, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("smerpaccount", "smerpbrand", "smerpmaterials"):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		product_info.append({"name": field_name, "label": label, "value": field_value})

	# 证书
	product_licenses = []
	for item in smerpprduct.smerpproductlicenses.all():
		product_licenses.append([item.name, item.img])

	# 产品图片
	product_imgs = []
	for item in smerpprduct.smerpproductimgs.all():
		product_imgs.append([item.img, item.create_time])

	# 原料
	materials = []
	for item in smerpprduct.smerpmaterials.all():
		materials.append([item.name, item.producer, item.source_type, item.ref_image, item.ref_url])

	publish_smcode_logs = []
	for item in smerpprduct.smerppublishsmcodelogs.all():
		publish_smcode_logs.append([item.create_time, item.area, item.price, item.num, item.start_no, item.end_no])

	context = {
		"product_info": product_info,
		"product_licenses": product_licenses,
		"product_imgs": product_imgs,
		"materials": materials,
		"publish_smcode_logs": publish_smcode_logs,
	}
	return render(request, "smAdmin/check/product_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['check.product.check', ])
def product_submit_check_result(request):
	"""
	提交产品信息的审核结果
	:param request:
	:return:
	"""
	id = request.POST.get('id')  # 产品信息Id
	is_pass = request.POST.get('is_pass')  # 是否通过
	check_mark = request.POST.get('check_mark')  # 审核备注

	if not check_mark or len(check_mark) < 2:
		res = {"c": -1, "m": u"审核备注信息过短"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	if not id:
		res = {"c": -1, "m": u"参数错误，产品信息不存在"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	try:
		smerpproduct = SmerpProduct.objects.get(id=id)
		if not smerpproduct:
			res = {"c": -1, "m": u"参数错误，产品信息不存在"}
			return HttpResponse(json.dumps(res), content_type="application/json")

		if is_pass == "1":
			smerpproduct.check_status = 2  # 审核通过
		else:
			smerpproduct.check_status = 3  # 驳回

		smerpproduct.check_mark = check_mark
		smerpproduct.check_time = datetime.now()
		smerpproduct.save()

		res = {"c": 0, "m": u"审核结果已经保存"}
		return HttpResponse(json.dumps(res), content_type="application/json")
	except:
		logger.exception("")

	res = {"c": -99, "m": u"系统异常"}
	return HttpResponse(json.dumps(res), content_type="application/json")
